﻿Imports System
Imports System.Windows
Imports System.Windows.Controls
Imports System.Windows.Media
Imports System.Windows.Media.Animation
Imports System.Windows.Shapes
Imports SilverMemory.Engine

Partial Public Class SelectPlayers
  Inherits UserControl
  Implements IPlayerFactory

  'keep a list of artificial players, so they aren't garbage collected
  Private artificialPlayers As New List(Of ArtificialPlayer)
  Private playersList As New List(Of Player)

  ''' <summary>
  ''' Event that fires when the players are ready
  ''' </summary>
  Public Event PlayersReady(ByVal sender As Object, ByVal e As EventArgs)

  Public Sub New()
    ' Required to initialize variables
    InitializeComponent()

    TextBlockAddPlayer.Text = My.Resources.Texts.PlayerConfigurationCaption
    ButtonOK.Content = My.Resources.Texts.ButtonStart

    'fill in default names for human players
    PlayerSelection1.PlayerName = String.Format(My.Resources.Texts.DefaultPlayerName, 1)
    PlayerSelection2.PlayerName = String.Format(My.Resources.Texts.DefaultPlayerName, 2)
    PlayerSelection3.PlayerName = String.Format(My.Resources.Texts.DefaultPlayerName, 3)
    PlayerSelection4.PlayerName = String.Format(My.Resources.Texts.DefaultPlayerName, 4)
  End Sub

  Private game As Game
  ''' <summary>
  ''' keep the game, needed to pass on to artificial players
  ''' </summary>
  Public Sub SetGame(ByVal game As Game)
    Me.game = game
  End Sub

  Private Sub ButtonOK_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
    addPlayer(PlayerSelection1, 1)
    addPlayer(PlayerSelection2, 2)
    addPlayer(PlayerSelection3, 3)
    addPlayer(PlayerSelection4, 4)

    If Me.playersList.Count > 0 Then
      RaiseEvent PlayersReady(Me, New EventArgs)
    End If
  End Sub

  Public Function GetPlayers() As System.Collections.Generic.IList(Of Engine.Player) Implements Engine.IPlayerFactory.GetPlayers
    Return playersList
  End Function

  ''' <summary>
  ''' create a player by what has been selected
  ''' </summary>
  ''' <param name="plsel">the usercontrol with the selection</param>
  Private Sub addPlayer(ByVal plsel As PlayerSelection, ByVal index As Integer)
    Select Case plsel.PlayerType
      Case PlayerSelection.Players.Computer
        'computerplayer
        Dim player As New Player(String.Format(My.Resources.Texts.DefaultComputerPlayerName, index.ToString()))
        artificialPlayers.Add(New ArtificialPlayer(Me.game, player, plsel.ComputerPlayLevel - 1))
        Me.playersList.Add(player)

      Case PlayerSelection.Players.Player
        'human player
        Dim name = plsel.PlayerName
        If String.IsNullOrEmpty(name) Then
          name = String.Format(My.Resources.Texts.DefaultPlayerName, index.ToString())
        End If
        Me.playersList.Add(New Player(name))

      Case Else
        'nothign
    End Select
  End Sub
End Class
